package org.biubiu0002.baiblog.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.biubiu0002.baiblog.common.exception.BaiBlogException;
import org.biubiu0002.baiblog.common.exception.BizCodeEnumException;
import org.biubiu0002.baiblog.common.utils.PageUtils;
import org.biubiu0002.baiblog.common.utils.Query;
import org.biubiu0002.baiblog.core.dao.SysPermissionDao;
import org.biubiu0002.baiblog.core.model.entity.SysPermissionEntity;
import org.biubiu0002.baiblog.core.model.vo.PermissionVo;
import org.biubiu0002.baiblog.core.service.SysPermissionService;
import org.biubiu0002.baiblog.core.utils.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service("sysPermissionService")
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionDao, SysPermissionEntity> implements SysPermissionService {

    @Override
    public void save(PermissionVo permissionSaveReqVo) {
        SysPermissionEntity sysPermissionEntity = new SysPermissionEntity();
        BeanUtils.copyProperties(permissionSaveReqVo,sysPermissionEntity);
        sysPermissionEntity.setResourceId(IdGenerator.generateUid());
        baseMapper.insert(sysPermissionEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SysPermissionEntity> page = this.page(
                new Query<SysPermissionEntity>().getPage(params),
                new QueryWrapper<SysPermissionEntity>().eq("is_deleted",0)
        );

        return new PageUtils(page);
    }

    @Override
    public void update(PermissionVo permissionSaveReqVo) {
        SysPermissionEntity permissionEntity = getOne(new QueryWrapper<SysPermissionEntity>().eq("resource_id", permissionSaveReqVo.getPermissionId()));
        if(permissionEntity==null){
            throw new BaiBlogException(BizCodeEnumException.RECORD_NOT_EXIST_EXCEPTION);
        }
        if(StringUtils.equals(permissionEntity.getMethod(),permissionSaveReqVo.getMethod())){
            throw new BaiBlogException(BizCodeEnumException.METHOD_EXIST_EXCEPTION);
        }
        this.baseMapper.update(permissionEntity,new UpdateWrapper<SysPermissionEntity>()
                .set("method",permissionSaveReqVo.getMethod())
                .set("description",permissionEntity.getDescription())
        );
    }

}